<template>
    <div class="item-table" @click="showFilterSelect = false">
        <loading :show="loading"></loading>
        <div class="panel m-b-0">
            <div class="panel-heading clearfix">
                {{title}}
                <span> / <span
                        class="text-primary">{{total}}</span> items</span>
                <div class="pull-right table-columns" v-if="isColumns">
                    <div class="dropdown">
                        <button class="btn btn-primary" data-toggle="dropdown" v-tooltip.top="'Columns'">
                            <i class="fif fif-list-column"></i>
                        </button>
                        <ul class="dropdown-menu pull-right animated fadeIn" role="menu" aria-labelledby="dLabel">
                            <li :key="item.key" v-for="item in controlColumns" class="checkbox checkbox-info" @click.stop
                                style="border-bottom: 1px solid #eee">
                                <div @click.stop style="padding: 5px;">
                                    <input @click.stop=toggleColumns(item) type="checkbox" class="checkbox"
                                           :id="item.key" v-model="item.show"/>
                                    <label :for="item.key" style="display: block;">{{item.label}}</label>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="side-icon-text" style="display: inline-block;" v-if="isAdd">
                    <i class="fif fif-add-list text-info" style="font-size: 24px; cursor: pointer"
                       @click="$emit('add')" v-tooltip.top="'Add'">
                    </i>
                </div>
                <ul class="nav navbar-top-links navbar-right pull-right" v-if="isSearch">
                    <li>
                        <form role="search" class="app-search m-r-10">
                            <input type="text" placeholder="Search..." class="form-control bg-info" v-model="keyWord">
                            <a href="javascript:void(0)"><i class="fif fif-search" style="color:#fff"></i></a>
                        </form>
                    </li>
                </ul>


                <button v-if="isExport" class="pull-right btn btn-success m-r-10" style="padding: 4px 10px;" @click=" $emit('export')" v-tooltip.top="`Export`">
                    <i class="fif fif-export-excel" style="font-size: 18px;" ></i>
                </button>
                <div class="batch-btns pull-right m-r-10 animated fadeIn" v-show="this.selected.length">
                    <button :key="'btn' + index"  v-for="(btn, index) in batchButtons" class="btn m-r-5" @click="batch" :class="btn.cls">
                        {{btn.label}}
                    </button>
                </div>
            </div>
            <div :class="{'table-responsive': responsive}">
                <table class="table table-hover manage-u-table table-striped">
                    <thead>
                    <tr>
                        <th v-if="multipie">
                            <div class="checkbox checkbox-success" style="margin: 0;">
                                <input type="checkbox" v-model="selectAll" @click="toggleSelectAll" id="selectAll">
                                <label style="min-height: 15px; min-width: 10px;" for="selectAll"></label>
                            </div>
                        </th>
                        <th  :key="'column' + column.key" v-for="column in columns"
                            :class="getColumnClass(column)"
                            v-show="controlColumns[column.key] && controlColumns[column.key].show"
                        >
                            <span v-html="column.label ? column.label : column.key"></span>
                            <i class="fif" :class="getOrderClass(column)" @click="toggleOrder(column)"></i>

                            <div class="dropdown" style="display: inline-block;" v-if="column.filterSelect">
                                <i class="fif"
                                   :class="{'fif-angle-down': !showFilterSelect, 'fif-angle-up': showFilterSelect}"

                                   style="cursor: pointer; font-size: 10px;" data-toggle="dropdown"></i>

                                <ul v-if="column.filterSelect" class="dropdown-menu animated fadeIn" role="menu"
                                    aria-labelledby="dLabel">
                                    <li  :key="'filterselect' + index" v-for="(item, index) in column.filterSelect" class="checkbox checkbox-info" @click.stop
                                        style="border-bottom: 1px solid #eee">
                                        <div @click.stop style="padding: 5px;">
                                            <input type="checkbox" class="checkbox" :id="`${column.key + item.value}`"
                                                   v-model="item.selected"/>
                                            <label :for="`${column.key + item.value}`" style="display: block;">{{item.label}}</label>
                                        </div>
                                    </li>
                                    <li class="p-l-10" @click.stop>
                                        <span class="filter-btn" @click.stop="filterFromLabel(column)"
                                              style="cursor: pointer;">Filter</span>
                                        <!--<span class="filter-btn" @click.stop="resetFilterLabel(column.filterSelect)"-->
                                              <!--style="cursor: pointer;">Reset</span>-->
                                    </li>
                                </ul>
                            </div>

                        </th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr  :key="'tr' + trIndex" v-for="(item, trIndex) in data">
                        <td v-if="multipie">
                            <div class="checkbox checkbox-success" style="margin: 0;position: relative;">
                                <input type="checkbox" v-model="item.select" @click="toggleSelect"
                                       :id="'select'+item.id">
                                <label style="min-height: 15px; min-width: 10px;" :for="'select'+item.id"></label>
                            </div>
                        </td>
                        <td  :key="'td' + index" v-for="(column, index) in columns" v-if="!column.type || tdTypes.indexOf(column.type) === -1"
                            :class="getRowClass(column)"
                            v-show="controlColumns[column.key] && controlColumns[column.key].show"
                        >
                            <slot :name="column.key" :item="item" :column="column">
                                <span v-html="item[column.key]"></span>
                            </slot>
                        </td>
                        <td v-else-if="column.type === 'serial'" :class="getAlignClass(column.align)"
                            v-show="controlColumns[column.key] && controlColumns[column.key].show">
                            <slot name="#" :item="item" :columns="columns">
                                {{getSerial(trIndex)}}
                            </slot>
                        </td>
                        <td class="actions" v-else-if="column.type === 'actions'" :class="getAlignClass(column.align)"
                            v-show="controlColumns[column.key] && controlColumns[column.key].show">
                            <slot name="actions" :item="item" :columns="columns"></slot>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</template>

<script>
    import Loading from '@/components/widgets/Loading'
    import {loadColumns, saveColumns} from '@/cache'

    export default {
        name: "ItemTable",
        components: {Loading},
        created() {
            this.tdTypes = ['actions', 'serial', 'select']
        },
        mounted() {
            this.initColumns()
        },
        data() {
            return {
                orderBy: null,
                orderDirection: null,
                controlColumns: {},
                keyWord: '',
                selectAll: false,
                selected: [],

                showFilterSelect: false
            }
        },
        props: {
            model: {
                type: String,
                default: ''
            },
            title: {
                type: String,
                default: 'List'
            },
            isAdd: {
                type: Boolean,
                default: false
            },
            isColumns: {
                type: Boolean,
                default: false
            },
            isExport: {
                type: Boolean,
                default: false
            },
            isSearch: {
                type: Boolean,
                default: false
            },
            columns: {
                type: Array,
                default: () => []
            },
            data: {
                type: Array,
                default: () => []
            },
            loading: {
                type: Boolean,
                default: false
            },
            pageSize: {
                type: Number,
                default: 50,
            },
            page: {
                type: Number,
                default: 0,
            },
            total: {
                type: Number,
                default: 0,
            },
            multipie: {
                type: Boolean,
                default: false,
            },
            batchButtons: {
                type: Array,
                default: () => []
            },
            responsive: {
                type: Boolean,
                default: true
            }
        },
        methods: {
            initColumns() {
                if (this.columns.length) {
                    let cacheColumns = loadColumns()
                    this.columns.forEach(item => {
                        if (!item.hide) {
                            this.$set(this.controlColumns, item.key, {
                                label: item.label,
                                key: item.key,
                                show: cacheColumns[this.model] && cacheColumns[this.model].indexOf(item.key) !== -1 ? false : true,
                            })
                        }
                    })
                }
            },
            getSerial(index) {
                return this.page && this.pageSize ? (this.page - 1) * this.pageSize + (index + 1) : (index + 1)
            },
            getColumnClass(column) {
                let cls = ''
                // confirm whether need to order
                // if (column.sort) {
                //     cls = column.key !== this.orderBy && column.sortKey !== this.orderBy ?
                //         'sorting' : this.orderDirection === 'asc' ? 'sorting-desc' : 'sorting-asc'
                // }

                // get align class
                cls += ' ' + this.getAlignClass(column.thAlign)

                return cls
            },
            getOrderClass(column) {
                if (!column.sort) return ''

                return column.key !== this.orderBy && column.sortKey !== this.orderBy ?
                    'sorting' : this.orderDirection === 'asc' ? 'sorting-desc' : 'sorting-asc'
            },
            getRowClass(column){
                let clsArr = [];
                let alignCls = this.getAlignClass(column.tdAlign);
                let cls = column.extCls;
                if(alignCls) clsArr.push(alignCls);
                if(cls) clsArr.push(cls);
                return clsArr.length == 0 ? "" : clsArr.join("  ");
            },
            getAlignClass(dir) {
                return dir === 'center' ? 'text-center' : dir === 'right' ? 'text-right' : 'text-left'
            },
            toggleOrder(column) {
                // 没有sorting的列不可以排序
                if (!column.sort) {
                    return false
                }
                this.orderBy = column.sortKey ? column.sortKey : column.key
                if (this.orderDirection === 'asc') {
                    this.orderDirection = 'desc'
                    this.$emit("sort", ["ascend"], [this.orderBy])
                } else {
                    this.orderDirection = 'asc'
                    this.$emit("sort", ["descend"], [this.orderBy])
                }
            },
            toggleColumns(item) {
                this.$nextTick(() => {
                    saveColumns(this.model, item)
                })
            },
            toggleSelect() {
                this.$nextTick(() => {
                    this.selected = []
                    let isAll = true
                    this.data.forEach(item => {
                        if (item.select) {
                            this.selected.push(item)
                        } else {
                            isAll = false
                        }
                    })
                    this.selectAll = isAll
                })

            },
            toggleSelectAll() {
                this.$nextTick(() => {
                    this.data.forEach((item, index) => {
                        // let isAll =  this.selectAll ? true : false
                        // this.$set(this.data[index], 'select', isAll)
                        item.select = this.selectAll ? true : false
                    })
                    this.selected = this.selectAll ? this.data : []
                })
            },
            batch() {
                this.$emit('batch', this.selected)
            },

            initFilterLabel(filters) {
                for (let i = 0; i < filters.length; i++) {
                    this.$set(filters[i], 'selected', false)
                }
                return filters
            },
            filterFromLabel(column) {
                this.$emit("filter", column)
            },
            resetFilterLabel(filters) {

            }
        },
        watch: {
            keyWord() {
                this.$emit('search', this.keyWord)
            },
            columns() {
                this.initColumns()
            },
            model() {
                this.initColumns()
            },
            data() {
                let isAll = this.data.length ? true : false
                this.data.forEach(item => {
                    if (!item.select) {
                        isAll = false
                        return false
                    }
                })
                this.selectAll = isAll
            }
        }
    }
</script>

<style scoped lang="stylus">
    .item-table
        position: relative
        min-height: 100px;
        font-weight: 500;
        th
            white-space: nowrap;
            font-weight: 600;
        .app-search
            input[placeholder]
                color: #fff !important;
            input:
            :-webkit-input-placeholder
                color: #fff !important;
            a
                top: 16px;

    .sorting::after
        font-family: 'fif', serif;
        opacity: 0.2;
        margin-left: 0.8em;
        content: "\e796";
        cursor: pointer;

    .sorting-desc::after
        font-family: 'fif', serif;
        opacity: 0.8;
        margin-left: 0.8em;
        content: "\e790";
        cursor: pointer;

    .sorting-asc::after
        font-family: 'fif', serif;
        opacity: 0.8;
        margin-left: 0.8em;
        content: "\e795";
        cursor: pointer;

    .filter-btn:hover
        color: #00aeef
</style>
